package hyl.core.io;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import hyl.core.MyFun;

public class MyString {
	public static String filter(String str, int maxlen) {
		String s = filter(str);
		if (maxlen > 0 && s.length() > maxlen)
			return s.substring(0, maxlen);
		return s;
	}

	public static String filter(String str) {
		// 只允许字母和数字
		// String regEx = "[^a-zA-Z0-9]";
		// 清除掉所有特殊字符
		String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	public static String stream2String(InputStream inputStream, String encode) {
		ByteArrayOutputStream result = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int length;
		try {
			while ((length = inputStream.read(buffer)) != -1) {
				result.write(buffer, 0, length);
			}
			return result.toString("UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String stream2String(InputStream inputStream, int size, String charset) {
		if (inputStream != null && size > 0) {
			byte[] buf = new byte[size];
			try {
				inputStream.read(buf);
				if (charset == null || charset.length() == 0)
					return new String(buf);
				else {
					return new String(buf, charset);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static String read2String(BufferedReader reader) {
		String newLine = System.getProperty("line.separator");
		try {
			StringBuilder result = new StringBuilder();
			String line;
			boolean flag = false;
			while ((line = reader.readLine()) != null) {
				result.append(flag ? newLine : "").append(line);
				flag = true;
			}
			return result.toString();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static final Charset UTF8 = Charset.forName("UTF-8");

	public static byte[] getUTF8Bytes(String b) {
		return b.getBytes(UTF8);
	}

	public static String getUTF8String(byte[] b) {
		return new String(b, UTF8);
	}

	/**
	 * 查找第几个有相同字符的索引位置
	 * 
	 * @param c    带查找的字符
	 * @param from , 负数:从右边到左边 从第几个,正数:从左到右 第几个,不能为0
	 * @return 字符串中的字符索引
	 */
	public static int findChar(CharSequence s, char c, int from) {
		if (MyFun.isEmpty(s) || from == 0)
			return 0;
		if (from < 0) {
			int j = 0;
			for (int i = s.length() - 1; i >= 0; i--) {
				if (s.charAt(i) == c)
					j--;
				if (j == from)
					return i;
			}
		} else {
			int j = 0;
			for (int i = 0; i < s.length() - 1; i++) {
				if (j == from)
					return i;
				if (s.charAt(i) == c)
					j++;
			}
		}
		return 0;

	}
}
